package com.yunkaweilai.android.activity.operation.consumption.jici;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.operation.ReduceJiciSuccessActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.interfaces.JiciConsumeDialogInterfaces;
import com.yunkaweilai.android.interfaces.PopupJiciEmployee;
import com.yunkaweilai.android.model.CheckMemberSendBean;
import com.yunkaweilai.android.model.CheckSendBean;
import com.yunkaweilai.android.model.jici.CreateJiciStrModel;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.operation.AddEmployeeModel;
import com.yunkaweilai.android.model.operation.ReceivablesCreatOrderModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.operation.OperationJiciReduceDialog;
import com.yunkaweilai.android.view.popup.JiciEmployeePopup;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 继续消费生成订单
 * Created by Administrator on 2017/8/1.
 */

public class JiciOperaOrderActivity extends BaseActivity implements PopupJiciEmployee, JiciConsumeDialogInterfaces {


    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    private boolean sms = false;
    private boolean wechat = false;
    private boolean print = false;

    private String SelectedGoodsStr = "";
    private MemberHeadModel model;
    private CommonAdapter<CreateJiciStrModel.DataBean.GoodsListBean> adapter;
    private ArrayList<CreateJiciStrModel.DataBean.GoodsListBean> list = new ArrayList<>();
    private Gson gson = new Gson();
    public static final String JICI_ORDER_OPERA_BUNDLE = "JICI_ORDER_OPERA_BUNDLE";
    public static final String JICI_ORDER_OPERA_MODEL = "JICI_ORDER_OPERA_MODEL";
    public static final String JICI_STRING_STR_GOOD = "JICI_STRING_STR_GOOD";

    public static void actionStart(Context context, MemberHeadModel model, String SelectedGoodsStr) {
        Intent intent = new Intent(context, JiciOperaOrderActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(JICI_ORDER_OPERA_MODEL, model);
        bundle.putString(JICI_STRING_STR_GOOD, SelectedGoodsStr);
        intent.putExtra(JICI_ORDER_OPERA_BUNDLE, bundle);
        context.startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jici_opera_order);
        ButterKnife.bind(this);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        new TitleBuilder(mAc).setTitleText("计次消费")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightText("确定").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isRight();

            }
        });
        Bundle bundleExtra = getIntent().getBundleExtra(JICI_ORDER_OPERA_BUNDLE);
        model = (MemberHeadModel) bundleExtra.getSerializable(JICI_ORDER_OPERA_MODEL);
        SelectedGoodsStr = bundleExtra.getString(JICI_STRING_STR_GOOD);
        initHeadView();
        initAdapter();
        initGetTuisong2();
        initHttp();
    }

    //头部信息
    private void initHeadView() {
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);

        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());
    }

    private void isRight() {
        if ("1".equals(model.getIs_jici_password()) && !Utils.isEmpty(model.getPay_password())) {
            OperationJiciReduceDialog dialog = new OperationJiciReduceDialog(mAc, "是否确认扣次？", this, sms, wechat, print,true);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }else {
            OperationJiciReduceDialog dialog = new OperationJiciReduceDialog(mAc, "是否确认扣次？", this, sms, wechat, print,false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }

    private void initGetTuisong2() {
        HttpRequest.postUrl(Api.CHECK_SEND)
                .addParams("view", "consumemember")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            CheckSendBean checkSendBean = gson.fromJson(json, CheckSendBean.class);
                            if (checkSendBean.getData().getIs_check_print().equals("1")) {
                                print = true;
                            } else {
                                print = false;
                            }
                            if (checkSendBean.getData().getIs_send_sms().equals("1")) {
                                selectMember(model.getCard_no(), true);
                            } else {
                                selectMember(model.getCard_no(), false);
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void selectMember(String card_no, final boolean open_sms) {
        HttpRequest.postUrl(Api.CONSUME_MEMBER)
                .addParams("keyword", card_no)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            CheckMemberSendBean checkMemberSendBean = gson.fromJson(json, CheckMemberSendBean.class);
                            if (!StringUtils.isEmpty(checkMemberSendBean.getData().getMemberInfo().getMember_tel()) && open_sms) {
                                sms = true;
                            } else {
                                sms = false;
                            }
                            if (checkMemberSendBean.getData().getMemberInfo().getIs_push_wechat() == 1) {
                                wechat = true;
                            } else {
                                wechat = false;
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    //创建订单
    private void initCreateOrder(boolean isflag, String time, String password) {
        PostProcess member_id = HttpRequest.postUrl(Api.CREATE_JICI_ORDER)
                .addParams("member_id", model.getId())
//                .addParams("orderInfo[Tid]", initOrderModel.getData().getOrderno())
//                .addParams("orderInfo[ConsumeTime]", initOrderModel.getData().getDatetime() + "")
                .addParams("orderInfo[SelectedGoodsStr]", SelectedGoodsStr)
                .addParams("balance_password", password);

        if (isflag) {
            member_id.addParams("sendConsumeInfo[ConsumeAgain]", "ConsumeAgain");
            member_id.addParams("sendConsumeInfo[consume_again_time]", time);
        }
        member_id
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            ReceivablesCreatOrderModel receivablesCreatOrderModel = gson.fromJson(json, ReceivablesCreatOrderModel.class);
                            showToast("收款成功");
                            ReduceJiciSuccessActivity.actionStart(mAc, receivablesCreatOrderModel.getData().getTid(), sms, wechat, print);
                            finish();
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {

                        dismissProgressDialog();
                    }
                });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<CreateJiciStrModel.DataBean.GoodsListBean>(mAc, R.layout.item_list_jici_right_goods, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final CreateJiciStrModel.DataBean.GoodsListBean item, int position) {
                viewHolder.setText(R.id.id_tv_name, item.getGoods_name());
                if (item.getEmployee_name() == null) {
                    viewHolder.setText(R.id.id_tv_commission, "");
                } else {
                    viewHolder.setText(R.id.id_tv_commission, item.getEmployee_name() + "");
                }
                viewHolder.setText(R.id.id_tv_nums, item.getGoods_num() + "");
                View view = viewHolder.getView(R.id.id_llayout_commission);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JiciEmployeePopup shopPopup = new JiciEmployeePopup(mAc, item, item.getEmployee_str());
                        shopPopup.setInterface(JiciOperaOrderActivity.this);
                        shopPopup.showPopupWindow();
                    }
                });

            }
        };
        idListview.setAdapter(adapter);
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.CREATE_SELECTED_JICI)
                .addParams("member_id", model.getId())
                .addParams("SelectedGoodsStr", SelectedGoodsStr)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            CreateJiciStrModel createJiciStrModel = gson.fromJson(json, CreateJiciStrModel.class);
                            if (createJiciStrModel != null) {
                                list.clear();
                                list.addAll(createJiciStrModel.getData().getGoodsList());
                            }
                            adapter.notifyDataSetChanged();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }

                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(R.string.http_error);
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });


    }

    //添加提成人
    private void addSelectedEmployee(final String SelectedEmployeeStr, CreateJiciStrModel.DataBean.GoodsListBean model) {
        showProgressDialog();
        HttpRequest.postUrl(Api.ADD_SELECTED_EMPLOYEE)
                .addParams("SelectedEmployeeStr", SelectedEmployeeStr)
                .addParams("SelectedGoodsId", model.getGoods_id())
                .addParams("SelectedGoodsStr", SelectedGoodsStr)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            AddEmployeeModel addEmployeeModel = gson.fromJson(json, AddEmployeeModel.class);
                            SelectedGoodsStr = addEmployeeModel.getData().getList();
                            adapter.notifyDataSetChanged();
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        dismissProgressDialog();
                    }
                });
    }

    @Override
    public void selectEmplyee(CreateJiciStrModel.DataBean.GoodsListBean model, String employeeStr) {
        addSelectedEmployee(employeeStr, model);
    }

//    @Override
//    public void payMoney() {
//
//    }


    @Override
    public void getJiciCheck(boolean isflag, String time, String password) {
        showProgressDialog("请稍等，正在创建订单");
        initCreateOrder(isflag, time, password);
    }

}
